<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {useRoute} from 'vue-router'
import http from '../utils/http.ts'
import MessageBox from '../components/MessageBox.vue'

const route = useRoute()
const id = <string>route.query.id

const upgradeRecords = ref<UpgradeRecord[]>([])

async function list() {
  const d = await http<PageResult<UpgradeRecord>>({
    url: '/upgradeRecord/page', params: {serverId: id},
  })
  upgradeRecords.value = d.records
}

onMounted(() => {
  list()
})

function restoreTo(id: number) {
  messageBox.value?.openMessageBox('restore', id)
}

const messageBox = ref<InstanceType<typeof MessageBox>>()

// 配置还原记录为警告色
const tableRowClassName = ({row}: {
  row: UpgradeRecord
}) => {
  if (row.upgradeType === 2) {
    return 'warning-row'
  }
  return ''
}
</script>

<template>
  <message-box ref="messageBox" @action-done="list"/>

  <el-table :data="upgradeRecords"
            :row-class-name="tableRowClassName"
  >
    <el-table-column prop="id" label="id"/>

    <el-table-column prop="backupPath" label="备份的文件夹"/>
    <el-table-column prop="upgradeTime" label="服务更新时间"/>

    <!--（1：更新，2：还原）-->
    <el-table-column prop="upgradeType" label="更新记录的类型">
      <template #default="scope">
        <el-tag v-if="scope.row.upgradeType === 1"
                type="primary"
                effect="plain"
                round>
          更新
        </el-tag>
        <el-tag v-if="scope.row.upgradeType === 2"
                type="warning"
                effect="plain"
                round>
          还原
        </el-tag>
      </template>
    </el-table-column>

    <!--还原记录的更新记录的 id（还原记录还原的是哪条更新记录）-->
    <el-table-column prop="upgradeRecordIdForRestoreRecord" label="更新记录的 id"/>
    <el-table-column prop="restoreRecordId" label="还原记录的 id"/>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button v-if="!scope.row.restoreRecordId"
                   @click="restoreTo(scope.row.id)"
                   type="danger"
                   plain circle
        >
          <i class="iconfont icon-banbenhuitui"></i>
        </el-button>
        <el-tag v-else
                type="danger"
                effect="plain"
                round>
          已还原
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
</template>

<style lang="stylus">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>